package com.jamiexu.lua.interpreter;

import java.util.LinkedList;
import java.util.List;

public class  LUOMain {
    static class Node {
        String data;
        int type;
        Node father;
        List<Node> child;

        public Node(String data) {
            this.data = data;
            this.child = new LinkedList<>();
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            int index = 0;
            for (Node n : child)
                builder.append(n.toString()).append((index++ < child.size() - 1) ? "," : "");
            return "{" +
                    "data:\"" + data + "\"" +
                    ", child:[" + builder + ""
                    + "]}";
        }
    }

    public static void main(String[] args) {
        char[] lex = "(1+(1+3))".toCharArray();
        Node root = new Node("root");
        Node current = root;
        StringBuilder builder = new StringBuilder();
        boolean b = false;
        for (char c : lex) {
            if (c == '(') {
                if (b) {
                    current.child.add(new Node(builder.toString()));
                    builder = new StringBuilder();
                    b = false;
                }
                Node newNode = new Node("(");
                newNode.father = current;
                newNode.type = 1;
                current.child.add(newNode);
                current = newNode;
            } else if (c == ')') {
                if (b) {
                    current.child.add(new Node(builder.toString()));
                    builder = new StringBuilder();
                    b = false;
                }
                current = current.father;
            } else if (c == '+') {
                if (b) {
                    current.child.add(new Node(builder.toString()));
                    builder = new StringBuilder();
                    b = false;
                }
                Node newNode = new Node("+");
                newNode.father = current;
                newNode.type = 0;
                current.child.add(newNode);
            } else if (c == '-') {
                if (b) {
                    current.child.add(new Node(builder.toString()));
                    builder = new StringBuilder();
                    b = false;
                }
                Node newNode = new Node("-");
                newNode.father = current;
                newNode.type = 0;
                current.child.add(newNode);
            } else {
                builder.append(c);
                b = true;
            }
        }
        System.out.println(root.toString());
    }
}
